//
//  UIScrollViewAdditions.m
//  Tint
//
//  Created by Kevin Wu on 2/22/12.
//  Copyright (c) 2012 Telligenty. All rights reserved.
//

#import "UIScrollViewAdditions.h"


@implementation UIScrollView (Tint)



#pragma mark - Content size

- (void)setContentSizeIfNeeded:(CGSize)contentSize
{
    if ( !CGSizeEqualToSize(self.contentSize, contentSize) ) {
        self.contentSize = contentSize;
    }
}

- (void)makeContentSizeToViewSizeIfNeeded
{
    CGSize newContentSize = CGSizeZero;
    newContentSize.width = MAX(self.contentSize.width, self.bounds.size.width);
    newContentSize.height = MAX(self.contentSize.height, self.bounds.size.height);
    [self setContentSizeIfNeeded:newContentSize];
}

- (void)resetContentSizeWithBottomPadding:(CGFloat)bottomPadding rightPadding:(CGFloat)rightPadding
{
    CGFloat maxRight = CGFLOAT_MIN;
    CGFloat maxBottom = CGFLOAT_MIN;
    
    for ( UIView *sv in self.subviews ) {
        CGFloat rightX = CGRectGetMaxX(sv.frame);
        CGFloat bottomY = CGRectGetMaxY(sv.frame);
        maxRight = MAX(maxRight, rightX);
        maxBottom = MAX(maxBottom, bottomY);
    }
    
    CGFloat w = maxRight + rightPadding;
    CGFloat h = maxBottom + bottomPadding;
    
    w = MAX(w, self.bounds.size.width);
    h = MAX(h, self.bounds.size.height);
    
    [self setContentSizeIfNeeded:CGSizeMake(w, h)];
}

- (void)makeHorizontalScrollable
{
    if ( self.contentSize.width <= self.bounds.size.width ) {
        [self setContentSizeIfNeeded:CGSizeMake(self.bounds.size.width+1.0, self.contentSize.height)];
    }
}

- (void)makeVerticalScrollable
{
    if ( self.contentSize.height <= self.bounds.size.height ) {
        [self setContentSizeIfNeeded:CGSizeMake(self.contentSize.width, self.bounds.size.height+1.0)];
    }
}



#pragma mark - Scrolling

- (void)scrollToTopAnimated:(BOOL)animated
{
    [self setContentOffset:CGPointZero animated:animated];
}

- (void)scrollToCenterAnimated:(BOOL)animated
{
    CGPoint offset = CGPointZero;
    CGFloat height = CGRectGetHeight(self.bounds);
    offset.y = self.contentSize.height - height - height/2.0;
    [self setContentOffset:offset animated:animated];
}

- (void)scrollToBottomAnimated:(BOOL)animated
{
    CGPoint offset = CGPointZero;
    CGFloat height = CGRectGetHeight(self.bounds);
    offset.y = self.contentSize.height - height;
    [self setContentOffset:offset animated:animated];
}

- (void)stopScrollingAnimated:(BOOL)animated
{
    CGPoint offset = self.contentOffset;
    [self setContentOffset:offset animated:animated];
}

@end
